package pl.edu.pb.wi.cookbook.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class ParsingDateHeaderFix implements Filter {
    private static final String IF_MODIFIED_SINCE = "If-Modified-Since";

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain filter) throws IOException, ServletException {
        request = new HttpServletRequestWrapper((HttpServletRequest) request) {
            @Override
            public String getHeader(String name) {
                if (IF_MODIFIED_SINCE.equals(name)) {
                    return null;
                }
                return super.getHeader(name);
            }

            @SuppressWarnings("rawtypes")
            @Override
            public Enumeration getHeaderNames() {
                List<String> names = new ArrayList<String>();
                for (Enumeration<?> e = super.getHeaderNames(); e
                        .hasMoreElements();) {
                    String name = e.nextElement().toString();
                    if (!IF_MODIFIED_SINCE.equals(name)) {
                        names.add(name);
                    }
                }
                return Collections.enumeration(names);
            }
        };
        filter.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }

}
